package com.sinopec.handdevice;


import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;

import androidx.multidex.MultiDex;

import com.alibaba.android.arouter.launcher.ARouter;
import com.github.promeg.pinyinhelper.Pinyin;
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict;
import com.myutils.UHFHelp;
import com.nativec.tools.ModuleManager;
import com.orhanobut.hawk.Hawk;
import com.sinopec.basemodule.BaseApplication;
import com.sinopec.basemodule.BuildConfig;
import com.sinopec.basemodule.base.AppManager;
import com.sinopec.basemodule.common.CrashHandler;
import com.sinopec.basemodule.common.Logger;
import com.sinopec.basemodule.constants.DeviceEnum;
import com.sinopec.basemodule.constants.SoundEnum;
import com.sinopec.basemodule.http.api.RetroAPIFactory;
import com.sinopec.basemodule.utils.SharedPreferenceUtil;
import com.sinopec.basemodule.utils.SoundPoolUtils;
import com.sinopec.basemodule.utils.ToastUtils;
import com.sinopec.handdevice.view.CustomAppUpdateActivity;
import com.sinopec.handdevice.view.GuideActivity;
import com.sinopec.handdevice.view.SplashActivity;
import com.sinopec.handdevice.view.WelcomeActivity;
import com.tencent.bugly.Bugly;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by lwj
 */

public class MyApp extends BaseApplication {

    private String TAG = "SaasApp";

    /**
     * 友盟分享平台初始化
     */
//    {
    //微信
    //PlatformConfig.setWeixin("wx51b2f44500d354b2", "2d04642e6f159e8546dec29de2b906de");//我的测试账号
//        PlatformConfig.setWeixin("wx249c978c39903b95", "467d87ca73fd592a34839f054a16ea9c");//正式
//    }
    @Override
    public void onCreate() {
        super.onCreate();

        /**
         * 检查设备的合法性，如果不是专用设备则会抛出异常
         */
        boolean isCheckPhone = DeviceEnum.deviceType() != DeviceEnum.PHONE;
        if (!isCheckPhone) {
            //禁用普通手机使用代码
            Handler h = new Handler(this.getMainLooper());
            ToastUtils.showToast("此设备不被授权使用，即将退出，若有疑问，请联系管理员！");
            h.post(() -> {
                throw new Error();
            });
        }

        String packageName = getPackageName();
        Logger.d("baoming :" + packageName);
        SharedPreferenceUtil.initSharedPreference(this);
        Hawk.init(this).build();
        if (!BuildConfig.isDebug || Hawk.get("isSaveCrash", false)) {
            initCrashHandler();
            Logger.d(TAG, "Turn on the crash handler！");
        }

//        initDatabase("yelopack.db");
        RetroAPIFactory.init();
        initManager();
        initJpush();
        initBugly();
        //initUmeng();
        initARouter();
        // 添加中文城市词典
        Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(this)));

        initHandScanner();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        //关闭手持连接，和声音播放工具类（暂时只有手持有声音播放）
        closeHandConnect();
        ModuleManager.newInstance().setUHFStatus(false);
    }

    private void initARouter() {
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this); // 尽可能早，推荐在Application中初始化
    }

    /**
     * 关闭手持连接，和声音播放工具类（暂时只有手持有声音播放）
     */
    private void closeHandConnect() {
        if (DeviceEnum.deviceType() == DeviceEnum.COMMON) {
            UHFHelp.closeConnect();
            SoundPoolUtils.getInstance().onDestroy();
        }
    }

    /**
     * 如果是手持设备，初始化手持设备
     */
    private void initHandScanner() {
        if (DeviceEnum.deviceType() == DeviceEnum.COMMON) {
            //初始化声音
            initSound();

            UHFHelp.initReaderHelper(this);
        }
    }

    /**
     * 初始化声音
     */
    private void initSound() {
        SoundPoolUtils.getInstance().initHintSing(getApplicationContext(), SoundEnum.BEEPER.getKey(), SoundEnum.BEEPER.getKey());
        SoundPoolUtils.getInstance().initHintSing(getApplicationContext(), SoundEnum.BEEPER_SHORT.getKey(), SoundEnum.BEEPER_SHORT.getKey());
        SoundPoolUtils.getInstance().initHintSing(getApplicationContext(), SoundEnum.FAILURE.getKey(), SoundEnum.FAILURE.getKey());
        SoundPoolUtils.getInstance().initHintSing(getApplicationContext(), SoundEnum.SUCCESS.getKey(), SoundEnum.SUCCESS.getKey());
    }

//    /**
//     * 友盟
//     */
//    private void initUmeng() {
//
//        /*
//         * 设置组件化的Log开关
//         * 参数: boolean 默认为false，如需查看LOG设置为true
//         */
//        UMConfigure.setLogEnabled(true);
//
//        /*
//         * 设置日志加密
//         * 参数：boolean 默认为false（不加密）
//         */
//        UMConfigure.setEncryptEnabled(false);
//
//        /*
//         * 初始化common库
//         * 参数1:上下文，不能为空
//         * 参数2:【友盟+】 AppKey
//         * 参数3:【友盟+】 Channel
//         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
//         * 参数5:Push推送业务的secret,需要集成Push功能时必须传出Push的secret，否则传空。
//         */
//        //UMConfigure.init(this, BuildConfig.DEBUG ? AppConstants.UMENG_DEBUG_KEY : AppConstants.UMENG_RELEASE_KEY, getChannel(AppConstants.UMENG_CHANEL), UMConfigure.DEVICE_TYPE_PHONE, "");
//    }

    /**
     * 极光推送
     */
    private void initJpush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    private void initCrashHandler() {
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);  //为了防止dex突破65535的限制
    }

    private void initBugly() {
        //Logger.d("yelopack-bugly", "init bugly version name = " + BuildConfig.VERSION_NAME + ", version code = " + BuildConfig.VERSION_CODE + ", isDebug = " + BuildConfig.isDebug);
//        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
////        Beta.autoCheckUpgrade = false;
//        Beta.upgradeDialogLayoutId = R.layout.dialog_bugly_upgrade;
//        Beta.initDelay = 10 * 1000;
//        Beta.strUpgradeDialogUpgradeBtn = "立即升级";
//        Beta.strUpgradeDialogCancelBtn = "";
//        Beta.enableHotfix = false;//关闭热更新能力
        Bugly.init(getApplicationContext(), BuildConfig.BuglyAppID, BuildConfig.isDebug);
    }


    //key为渠道名的key，对应友盟的 UMENG_CHANNEL
    private String getChannel(String key) {
        try {
            PackageManager pm = getPackageManager();
            ApplicationInfo appInfo = pm.getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return "";
    }


    @Override
    public void appUpdateEvent(boolean isUserClick) {
        if (isUserClick) {//用户手动点击更新
            if (checkUpdate()) {//满足更新条件
                showUpdateWindow();
            } else {
                ToastUtils.showToast("暂无更新");
            }
        } else if (checkAutoUpdate()) {
            isShowAutoUpdateFlag = true;
            showUpdateWindow();
        }
    }

    /**
     * 展示自动更新弹窗
     */
    private void showUpdateWindow() {
        boolean isForce = getAppUpdateBean().isForce();
        String appDesc = getAppUpdateBean().getAppUpdateDesc();
        String appUpdateUrl = getAppUpdateBean().getAppDownloadUrl();

        CustomAppUpdateActivity.Companion.start(
                this,
                isForce,
                appDesc,
                appUpdateUrl
        );
    }

    /**
     * 判断是否满足升级条件
     *
     * @return
     */
    private boolean checkUpdate() {
        try {
            return getAppUpdateBean().isNeedUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断是否满足自动更新条件
     *
     * @return
     */
    private boolean checkAutoUpdate() {
        return checkUpdateTopActivity()
                && checkUpdate()
                && (getAppUpdateBean().isForce() || !isShowAutoUpdateFlag);
    }

    /**
     * 自动更新弹窗排除 GuideActivity，SplashActivity，WelcomeActivity,LoginActivity
     *
     * @return true, 允许弹出更新提醒的activity，false 反之
     */
    private boolean checkUpdateTopActivity() {
        return checkUpdateTopActivity(
                GuideActivity.class,
                SplashActivity.class,
                WelcomeActivity.class);
    }

    private boolean checkUpdateTopActivity(Class... clzs) {
        try {
            if (null == clzs || clzs.length == 0) {
                return false;
            }

            Set<Boolean> clazzSet = new HashSet<>();
            Activity lastActivity = AppManager.getInstance().getTopActivity();
            for (Class clazz : clzs) {
                clazzSet.add(lastActivity.getClass().getName().equals(clazz.getName()));
            }
            return !clazzSet.contains(true);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
